package com.bbc.service.type.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bbc.base.page.MysqlPaginatedArrayList;
import com.bbc.base.page.PaginatedList;
import com.bbc.entity.type.TypeInfo;
import com.bbc.entity.type.TypeQuery;
import com.bbc.mapper.type.TypeMapper;
import com.bbc.service.type.TypeService;
import com.bbc.third.taobao.TBApi;
import com.taobao.api.domain.ItemCat;
import com.taobao.api.response.ItemcatsGetResponse;

@Service
public class TypeServiceImpl implements TypeService {
	
	@Autowired
	private transient TypeMapper typeMapper;
	
	@Autowired
	private transient TBApi tBApi;

	@Override
	public Integer addType(TypeInfo typeInfo) {
		return typeMapper.addType(typeInfo);
	}

	@Override
	public List<TypeInfo> findType(TypeQuery query) {
		return typeMapper.findType(query);
	}

	@Override
	public TypeInfo findTypeById(Integer typeId) {
		return typeMapper.findTypeById(typeId);
	}

	@Override
	public TypeInfo findTypeByCid(String cid, String fromKey) {
		TypeQuery q = new TypeQuery();
		q.setCid(cid);
		q.setFromKey(fromKey);
		return typeMapper.findTypeByCid(q);
	}

	@Override
	public void addtbType(String parentCid) {
		ItemcatsGetResponse res = tBApi.getType(parentCid);
		List<ItemCat> list = res.getItemCats();
		for (ItemCat ic:list) {
			TypeInfo ti = findTypeByCid(ic.getCid().toString(), tBApi.key);
			if (ti == null) {
				ti = new TypeInfo();
				ti.setCid(ic.getCid().toString());
				ti.setFromKey(tBApi.key);
				ti.setLevel(0);
				ti.setName(ic.getName());
				if (ic.getIsParent()) {
					ti.setParent(1);
				} else {
					ti.setParent(0);
				}
				ti.setParentCid(ic.getParentCid().toString());
				typeMapper.addType(ti);
				if (ti.getParent()==1) {
					addtbType(ti.getCid());
				}
			}
			System.out.println(ti.getCid());
		}
	}

	@Override
	public List<TypeInfo> findType(TypeQuery query, int page, int pageSize) {
		PaginatedList<TypeInfo> list = new MysqlPaginatedArrayList<TypeInfo>(page,pageSize);
		list.setTotalItem(typeMapper.findTypeCount(query));
		query.setStartRow(list.getStartRow());
		query.setEndRow(list.getEndRow());
		list.addAll(typeMapper.findType(query));
		return list;
	}

}
